#include "node_server.h"

std::unordered_map<std::string,tagServerConfig> m_ServerConfigs;
std::unordered_map<std::string,std::map<int,tagSubscriber> > m_Subscribers;
std::unordered_map<std::string,std::string> m_SubscribersPwd;

int main(int argc,char *argv[])
{
	char strTmp[1024];
	NetMessage myMes;

	if(argc < 3) 
	{
		printf("使用说明:center_server 0.0.0.0 1234\n");	
		return 1;
	}

	if(LoadServerConfig() == false)
	{
		printf("服务器配置导入失败!\n");
		return 1;	
	}

	InitMolNet("center_server");	

 	if(!StartMolNet(argv[1],atoi(argv[2])))
	{
	    sprintf(strTmp,"【系统】 中心服务器启动失败,IP地址:%s,端口:%d。",argv[1],atoi(argv[2]));
		LOG_BASIC(strTmp);

		CleanMolNet();
		return 1;
	}

	LOG_BASIC("中心服务器:ip:%s,端口:%d 启动成功。",argv[1],atoi(argv[2]));

	process_child_servers();

	while(IsConnected())
	{
		GetNetMessage(myMes);
		MolTcpSocketClientManager.GetNetMessage(myMes,false);

		for(int i=0;i<myMes.GetCount();i++)
		{
			MessageStru *mes = myMes.GetMesById(i);
			if(mes==NULL) continue;

			switch(mes->GetType())
			{
			case MES_TYPE_ON_CONNECTED:
				{
					printf("MES_TYPE_ON_CONNECTED:%d\n",mes->GetSocket());		
				}
				break;
			case MES_TYPE_ON_DISCONNECTED:
				{
					printf("MES_TYPE_ON_DISCONNECTED%d\n",mes->GetSocket());

					unsuscriptions(mes->GetSocket());
				}
				break;
			case MES_TYPE_ON_READ:
				{
					//printf("MES_TYPE_ON_READ\n");

				    Json::Reader reader;
				    Json::Value json_object;

				    if (!reader.parse(mes->GetMes()->getData(), json_object))
				    {
				        LOG_ERROR("数据解析失败:%s",mes->GetMes()->getData());
				        break;
				    }

					switch(json_object["MsgId"].asInt())
					{
					case IDD_MESSAGE_UNPUBSCRIPTIONS:
						{
							std::string pscription = json_object["scription"].asString();	
							int type = 	json_object["type"].asInt();

							unsuscriptions(mes->GetSocket(),type,pscription);	
						}
						break;
					case IDD_MESSAGE_SUSCRIPTIONS:                    
						{
							std::string pscription = json_object["scription"].asString();	
							std::string password = json_object["password"].asString();
							std::string puniqueid = json_object["uniqueid"].asString();
							int type = 	json_object["type"].asInt();

							suscriptions(mes->GetSocket(),type,puniqueid,pscription,password);
						}
						break;
					case IDD_MESSAGE_PUBSCRIPTIONS:
						{
							int type = 	json_object["type"].asInt();

							public_message(type,json_object);
						}
						break;
					default:
						break;
					}
				}
				break;
			default:
				break;
			}
		}

		usleep(1000);
	}

	CleanMolNet();

    return 0;
}